#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
健康检查API
用于Docker容器健康检查和服务监控
"""

from flask_restful import Resource
from flask import current_app
from app.utils.response_utils import create_response
from app.database import get_database, get_db_client
from datetime import datetime
import os

class HealthCheckAPI(Resource):
    """健康检查API"""
    
    def get(self):
        """
        健康检查端点
        GET /api/health
        """
        try:
            health_status = {
                "status": "healthy",
                "timestamp": datetime.now().isoformat(),
                "version": "v1.3.7-dev",
                "environment": os.getenv('FLASK_ENV', 'development'),
                "services": {}
            }
            
            # 检查数据库连接
            try:
                db_client = get_db_client()
                if db_client:
                    # 尝试ping数据库
                    db_client.admin.command('ping')
                    health_status["services"]["mongodb"] = {
                        "status": "healthy",
                        "connection": "active"
                    }
                else:
                    health_status["services"]["mongodb"] = {
                        "status": "unhealthy",
                        "connection": "failed"
                    }
                    health_status["status"] = "degraded"
            except Exception as e:
                current_app.logger.error(f"数据库健康检查失败: {e}")
                health_status["services"]["mongodb"] = {
                    "status": "unhealthy",
                    "error": str(e)
                }
                health_status["status"] = "degraded"
            
            # 检查数据库集合
            try:
                db = get_database()
                if db:
                    collections = db.list_collection_names()
                    required_collections = ['articles', 'user_favorites', 'search_history']
                    missing_collections = [col for col in required_collections if col not in collections]
                    
                    if missing_collections:
                        health_status["services"]["collections"] = {
                            "status": "unhealthy",
                            "missing": missing_collections
                        }
                        health_status["status"] = "degraded"
                    else:
                        health_status["services"]["collections"] = {
                            "status": "healthy",
                            "available": required_collections
                        }
                else:
                    health_status["services"]["collections"] = {
                        "status": "unhealthy",
                        "error": "无法获取数据库实例"
                    }
                    health_status["status"] = "degraded"
            except Exception as e:
                current_app.logger.error(f"集合检查失败: {e}")
                health_status["services"]["collections"] = {
                    "status": "unhealthy",
                    "error": str(e)
                }
                health_status["status"] = "degraded"
            
            # 检查应用配置
            try:
                config_status = {
                    "secret_key_configured": bool(current_app.config.get('SECRET_KEY') != 'dev-secret-key-change-in-production'),
                    "mongodb_uri_configured": bool(current_app.config.get('MONGODB_URI')),
                    "cors_configured": bool(current_app.config.get('CORS_ORIGINS'))
                }
                
                if all(config_status.values()):
                    health_status["services"]["configuration"] = {
                        "status": "healthy",
                        "details": config_status
                    }
                else:
                    health_status["services"]["configuration"] = {
                        "status": "warning",
                        "details": config_status
                    }
                    if health_status["status"] == "healthy":
                        health_status["status"] = "degraded"
            except Exception as e:
                current_app.logger.error(f"配置检查失败: {e}")
                health_status["services"]["configuration"] = {
                    "status": "unhealthy",
                    "error": str(e)
                }
                health_status["status"] = "degraded"
            
            # 根据整体状态返回相应的HTTP状态码
            if health_status["status"] == "healthy":
                return create_response(True, health_status, "服务运行正常", status_code=200)
            elif health_status["status"] == "degraded":
                return create_response(True, health_status, "服务运行但存在问题", status_code=200)
            else:
                return create_response(False, health_status, "服务异常", status_code=503)
                
        except Exception as e:
            current_app.logger.error(f"健康检查失败: {e}")
            error_response = {
                "status": "unhealthy",
                "timestamp": datetime.now().isoformat(),
                "error": str(e)
            }
            return create_response(False, error_response, "健康检查失败", status_code=503)
